Factory method pattern
part 8/15 · 25.1 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
protected override IProduct MakeProduct()
{
IProduct product = new Phone();
// Do something with the object after receiving it
product.SetPrice(20.30);
return product;
}
}
In this example, MakeProduct is used in concreteFactory. As a result, MakeProduct() may be invoked in order to retrieve it from the IProduct. Custom logic could run after the object is obtained in the concrete factory method. GetObject is made abstract in the factory interface.
Java
This Java example is similar to one in the book Design Patterns.
The MazeGame uses Room but delegates the responsibility of creating Room objects to its subclasses that create the concrete classes. The regular game mode could use this template method:
public abstract class Room {
abstract void connect(Room room);
}
public class MagicRoom extends Room {
public void connect(Room room) {}
}
public class OrdinaryRoom extends Room {
public void connect(Room room) {}
}
public abstract class MazeGame {
private final List<Room> rooms = new ArrayList<>();
public MazeGame() {
Room room1 = makeRoom();
Room room2 = makeRoom();
room1.connect(room2);
rooms.add(room1);
rooms.add(room2);
}
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────